/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.view;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import com.example.android.google.apis.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

/**
 * Example of how to use an {@link com.google.android.maps.MapView}. <h3>MapViewDemo</h3>
 * 
 * <p>
 * This demonstrates creating a Map based Activity.
 * </p>
 * 
 * <h4>Demo</h4> Views/MapView
 * 
 * <h4>Source files</h4>
 * <table class="LinkTable">
 * <tr>
 * <td >src/com.example.android.apis/view/MapViewDemo.java</td>
 * <td >The Alert Dialog Samples implementation</td>
 * </tr>
 * <tr>
 * <td >/res/layout/mapview.xml</td>
 * <td >Defines contents of the screen</td>
 * </tr>
 * </table>
 */
public class MapViewDemo extends MapActivity
{
    MapView mapView;

    Handler handler;

    private ImageButton zoomIn;

    private ImageButton zoomOut;

    private ImageButton sat;

    private ImageButton traffic;

    private ImageButton currentLocation;

    private GestureDetector gestureDetector;

    private MyLocationOverlay myLocationOverlay;

    private MyItemizedOverlay myItemizedOverlay;

    private ChPopupWindow chPopupWindow;

    private static int currentIndex;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.mapview);
        gestureDetector = new GestureDetector(this, new OnDoubleClickListener());
        init();
    }

    private class OnDoubleClickListener extends GestureDetector.SimpleOnGestureListener
    {

        @Override
        public boolean onDoubleTap(MotionEvent e)
        {
            mapView.getController().animateTo(
                mapView.getProjection().fromPixels((int) e.getX(), (int) e.getY()),
                new Runnable()
                {

                    @Override
                    public void run()
                    {
                        if (!mapView.getController().zoomIn())
                        {
                            zoomIn.setImageResource(R.drawable.map_zoom_in_icon_disabled);
                        }
                    }
                });
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e)
        {
            Projection projection = mapView.getProjection();
            OverlayItem overlayItem = new OverlayItem(projection.fromPixels(
                (int) e.getX(), (int) e.getY()), ++currentIndex + "", "Hello");
            myItemizedOverlay.addOverlay(overlayItem);

            super.onLongPress(e);
        }
    }

    private void init()
    {
        initMapView();
        initImageButtons();
        initMyLocationOverlay();
        initItemizedOverlay();
    }

    private void initMapView()
    {
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int screenWidth = displayMetrics.widthPixels;
        int screenHeight = displayMetrics.heightPixels;
        mapView = (MapView) this.findViewById(R.id.map_view);
        chPopupWindow = new ChPopupWindow(this, screenWidth, screenHeight);
        chPopupWindow.setContentView(this.getLayoutInflater().inflate(R.layout.setting,
            null));
        ((FrameLayout) this.findViewById(R.id.main)).addView(chPopupWindow);

        mapView.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                gestureDetector.onTouchEvent(event);
                return false;
            }

        });
        mapView.getController().setZoom(15);
    }

    private void initItemizedOverlay()
    {
        Drawable unfocusedBg = this.getResources().getDrawable(
            R.drawable.poi_small_icon_unfocused);
        myItemizedOverlay = new MyItemizedOverlay(unfocusedBg, this);
        myItemizedOverlay.setPopupWindow(chPopupWindow, mapView);
        mapView.getOverlays().add(myItemizedOverlay);

        myItemizedOverlay.clear();
    }

    private void initMyLocationOverlay()
    {
        myLocationOverlay = new MyLocationOverlay(this, mapView)
        {

            @Override
            public synchronized void onLocationChanged(Location paramLocation)
            {
                GeoPoint gp = new GeoPoint((int) (paramLocation.getLatitude() * 1000000),
                        (int) (paramLocation.getLongitude() * 1000000));
                mapView.getController().animateTo(gp);
                super.onLocationChanged(paramLocation);
            }

            @Override
            protected void drawMyLocation(Canvas paramCanvas, MapView paramMapView,
                    Location paramLocation, GeoPoint paramGeoPoint, long paramLong)
            {
                Paint paint = new Paint();
                Projection projection = mapView.getProjection();
                Point point = new Point();
                projection.toPixels(paramGeoPoint, point);

                Bitmap arrowBitmap = BitmapFactory.decodeResource(
                    MapViewDemo.this.getResources(), R.drawable.current_location);
                paramCanvas.drawBitmap(arrowBitmap, point.x, point.y, paint);

                // super.drawMyLocation(paramCanvas, paramMapView, paramLocation, paramGeoPoint, paramLong);
            }

        };

        mapView.getOverlays().add(myLocationOverlay);

        myLocationOverlay.runOnFirstFix(new Runnable()
        {

            @Override
            public void run()
            {
                MapViewDemo.this.runOnUiThread(new Runnable()
                {

                    @Override
                    public void run()
                    {
                        currentLocation.setEnabled(true);
                    }
                });
                mapView.getController().animateTo(myLocationOverlay.getMyLocation());
            }
        });
    }

    private void initImageButtons()
    {
        currentLocation = (ImageButton) findViewById(R.id.current_location);
        currentLocation.setEnabled(false);
        zoomIn = (ImageButton) findViewById(R.id.zoom_in);
        zoomIn.setImageResource(R.drawable.map_zoom_in_icon_focused);
        zoomOut = (ImageButton) findViewById(R.id.zoom_out);
        zoomOut.setImageResource(R.drawable.map_zoom_out_icon_focused);
        sat = (ImageButton) findViewById(R.id.sat);
        sat.setImageResource(mapView.isSatellite() ? R.drawable.map_gps_icon_focused
                : R.drawable.map_gps_icon_unfocused);
        traffic = (ImageButton) findViewById(R.id.traffic);
        traffic.setImageResource(mapView.isTraffic() ? R.drawable.map_traffic_icon_focused
                : R.drawable.map_traffic_icon_unfocused);

        currentLocation.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {
                mapView.getController().animateTo(myLocationOverlay.getMyLocation());
            }
        });
        zoomIn.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                if (!mapView.getController().zoomIn())
                {
                    ((ImageButton) v)
                            .setImageResource(R.drawable.map_zoom_in_icon_disabled);
                }
                else
                {
                    ((ImageButton) v)
                            .setImageResource(R.drawable.map_zoom_in_icon_focused);
                }
            }
        });
        zoomOut.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                if (!mapView.getController().zoomOut())
                {
                    ((ImageButton) v)
                            .setImageResource(R.drawable.map_zoom_out_icon_disabled);
                }
                else
                {
                    ((ImageButton) v)
                            .setImageResource(R.drawable.map_zoom_out_icon_focused);
                }
            }
        });
        sat.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                mapView.setSatellite(mapView.isSatellite() ? false : true);
                ((ImageButton) v).setImageResource(mapView.isSatellite() ? R.drawable.map_gps_icon_focused
                        : R.drawable.map_gps_icon_unfocused);
            }
        });
        traffic.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                mapView.setTraffic(mapView.isTraffic() ? false : true);
                ((ImageButton) v).setImageResource(mapView.isTraffic() ? R.drawable.map_traffic_icon_focused
                        : R.drawable.map_traffic_icon_unfocused);
            }
        });
    }

    @Override
    protected boolean isRouteDisplayed()
    {
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        return gestureDetector.onTouchEvent(event);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        myLocationOverlay.enableMyLocation();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        myLocationOverlay.disableMyLocation();
        currentLocation.setEnabled(false);
    }
}